package com.mall.project.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mall.common.core.asserts.ApiAssert;
import com.mall.common.core.enums.ErrorCodeEnum;
import com.mall.common.core.model.response.ApiResponses;
import com.mall.common.core.model.supers.SuperController;
import com.mall.common.security.annotation.PreAuth;
import com.mall.project.sys.cons.LevelCons;
import com.mall.project.sys.model.dto.MenuDTO;
import com.mall.project.sys.model.dto.RoleDTO;
import com.mall.project.sys.model.entity.Role;
import com.mall.project.sys.model.parm.RolePARM;
import com.mall.project.sys.service.IMenuService;
import com.mall.project.sys.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author Sam
 * @since 2021-04-13
 */
@Api(tags = {"角色"})
@RestController
@RequestMapping("/role")
public class RoleRestController extends SuperController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;

    @PreAuth
    @ApiOperation("查询所有角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "角色名称 模糊", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "角色状态", type = "int", paramType = "query"),
    })
    @GetMapping
    public ApiResponses<IPage<Role>> page(@RequestParam(value = "name", required = false) String name,
                                          @RequestParam(value = "status", required = false) Integer status) {
        LambdaQueryWrapper<Role> wrapper = Wrappers.<Role>lambdaQuery()
                .like(StringUtils.isNotBlank(name), Role::getName, name)
                .eq(Objects.nonNull(status), Role::getStatus, status)
                .orderByAsc(Role::getOrderNum);
        IPage<Role> roleIPage = roleService.page(this.getPage(), wrapper);
        return success(roleIPage);
    }

    @PreAuth
    @ApiOperation(value = "条件查询角色", response = Role.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "角色名称 模糊", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "角色状态", type = "int", paramType = "query")
    })
    @GetMapping("/list")
    public ApiResponses<List<Role>> list(@RequestParam(value = "name", required = false) String name,
                                         @RequestParam(value = "status", required = false) Integer status) {
        List<Role> dtoList = roleService.list(Wrappers.<Role>lambdaQuery()
                .like(StringUtils.isNotBlank(name), Role::getName, name)
                .eq(Objects.nonNull(status), Role::getStatus, status)
                .orderByAsc(Role::getOrderNum));
        return success(dtoList);
    }

    @PreAuth
    @ApiOperation("单条查询角色")
    @GetMapping("/{id}")
    public ApiResponses<RoleDTO> getById(@PathVariable("id") String id) {
        Role role = roleService.getById(id);
        ApiAssert.notNull(ErrorCodeEnum.BAD_SELECT_FAILURE, role);
        List<MenuDTO> menuDTOList = menuService.getListByRoleId(id);
        RoleDTO dto = role.convert(RoleDTO.class);
        dto.setMenuList(menuDTOList);
        return success(dto);
    }

    @PreAuth
    @ApiOperation("新增角色")
    @PostMapping
    public ApiResponses<Void> create(@RequestBody @Validated(value = RolePARM.Create.class) RolePARM rolePARM) {
        rolePARM.setLevel(LevelCons.USER);
        roleService.createRole(rolePARM);
        return success();
    }

    @PreAuth
    @ApiOperation("修改角色")
    @PutMapping("/{id}")
    public ApiResponses<Void> updateById(@PathVariable("id") String id, @RequestBody RolePARM rolePARM) {
        rolePARM.setId(id);
        rolePARM.setLevel(null);
        roleService.updateRole(rolePARM);
        return success();
    }

    @PreAuth
    @ApiOperation("删除角色")
    @DeleteMapping("/{id}")
    public ApiResponses<Void> deleteById(@PathVariable("id") String id) {
        roleService.delRole(id);
        return success();
    }

    @PreAuth
    @ApiOperation("分配权限")
    @PostMapping("/assign")
    public ApiResponses<Void> assign(@RequestBody RolePARM rolePARM) {
        roleService.assign(rolePARM.getId(), rolePARM.getMenuIdList());
        return success();
    }

    @PreAuth
    @ApiOperation("更改状态")
    @PutMapping("/changeStatus")
    public ApiResponses<Void> changeStatus(@RequestBody @Validated({RolePARM.ChangeStatus.class}) RolePARM rolePARM) {
        Role role = new Role();
        role.setId(rolePARM.getId());
        role.setStatus(rolePARM.getStatus());
        ApiAssert.isTrue(ErrorCodeEnum.INTERNAL_SERVER_ERROR, roleService.updateById(role));
        return success();
    }
}

